package com.hd.trans.network.bean;

import com.google.gson.Gson;

import java.util.Objects;

import retrofit2.Response;

/**
 * Author: yang
 * Date: 2019/2/18 15:39
 * Desc: 自定义异常(服务器返回错误)
 */
public class MyHttpException extends RuntimeException {

    private int code;
    private String message;
    private final transient Response<?> response;

    public MyHttpException(Response<?> response) throws Exception {
        Gson gson = new Gson();  //这个errorBody().string()只能获取一次，下一次就为空了
        DataResponse errorResponse = gson.fromJson(
                Objects.requireNonNull(response.errorBody()).string(), DataResponse.class);
        this.code = errorResponse.getCode();
        this.message = errorResponse.getMessage();
        this.response = response;
    }

    /**
     * HTTP status code.
     */
    public int code() {
        return code;
    }

    /**
     * HTTP status message.
     */
    public String message() {
        return message;
    }

    /**
     * The full HTTP response. This may be null if the exception was serialized.
     */
    public Response<?> response() {
        return response;
    }
}
